//
//  getReportVC.m
//  App get report
//
//  Created by hongfei tam on 2019/3/7.
//  Copyright © 2019 YQ05. All rights reserved.
//

#import "getReportVC.h"

#import <WebKit/WebKit.h>
#import <AVFoundation/AVFoundation.h>

#import "ItemViewController.h"
#import "MKConstant.h"
#import "network.h"
#import "DB/DataPersist.h"


@interface getReportVC ()<WKNavigationDelegate,WKUIDelegate>{
    NSData *itemHTMLData;
    NSString *itemHTMLURL;
    
    UIActivityIndicatorView *loadActivity;  //加载动画
    UIView *activityBg;
}
@property (strong, nonatomic)   WKWebView                   *webView;
@property (strong, nonatomic)   UIProgressView              *progressView;
@end

@implementation getReportVC

- (void)viewDidLoad {
    [super viewDidLoad];

        // 颜色
        self.navigationController.navigationBar.tintColor = [UIColor blackColor];
        self.view.backgroundColor = [UIColor whiteColor];
        //NSString *title = self.itemDatasource.title;
        //NSString *title = @"1";
        //NSString *title = self.itemDatasource;
        //self.navigationItem.title = title;  //设置navigationItem.title 标题
        [self.navigationController.navigationBar setTitleTextAttributes:@{
                                                                          NSFontAttributeName:[UIFont systemFontOfSize:19],NSForegroundColorAttributeName:[UIColor grayColor]                }];
        
        //网络初始化
        //等网络请求 通知后再加载数据
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(setitemdata) name:@"getitemDataNOTIF" object:nil];
        
        network *getdata = [[network alloc]init];
        //[getdata itemVcgetJsonData:@"id" item:self.itemDatasource];  //获取子页面数据
        [getdata itemVcgetJsonData:@"getreport" item:self.itemDatasource];  //获取子页面数据
        [self loadingView];  //等待网络结果动画
        
        
        // sv 空白
        //    self.automaticallyAdjustsScrollViewInsets = false;
        //    UIView *view_head = [[UIView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_WIDTH*0.6)];
        //    view_head.backgroundColor = [UIColor whiteColor];
        //    [self.view addSubview:view_head];
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(rightClick)];
        self.navigationItem.rightBarButtonItem = rightItem;
        
        // [self setitemdata];  不等网络请求直接加载数据
    }


-(void)setitemdata{
    //读取数组值
    NSMutableArray *itemArray = [[DataPersist readValueNSMutableArray:@"itemData"] mutableCopy];
    //NSLog(@"itemArray %@ ",itemArray);
    
    NSString *rc = [itemArray valueForKey:@"rc"];
    //NSLog(@"rc is %@",rc);
    
//    rc = [datadic valueForKey:@"rc"]; //[rc isEqualToString:@"1"]
//    //NSString *rcstr = [NSString stringWithFormat:@"%@",@"1"];
    NSString *rcstr = [NSString stringWithFormat:@"%@",rc];
    // NSLog(@"rcstr %@",rcstr);
    
    NSString *successstr = [NSString stringWithFormat:@"%@",@"0"];
    
    if ([rcstr isEqualToString:successstr]) {  //判断请求类型
        itemHTMLURL = [itemArray valueForKey:@"data"];
        NSLog(@"itemHTMLURL is %@",itemHTMLURL);
        
        [self startInitWKWebView];
    }else{
         [self showAlert:@"消息" message:@"沒有報告"];
    }

    
}


-(void)showAlert:(NSString *)title message:(NSString *)message{  //警告弹出框
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"點擊OK");
        [self gobackVC];
    }];
    [alertController addAction:okAction];
    [self presentViewController:alertController animated:true completion:nil];
}

-(void)gobackVC{
    dispatch_async(dispatch_get_main_queue(), ^{  //get 主线程
        //NSLog(@"currentThread %@ ",[NSThread currentThread]);
        //加载成功
        [self.navigationController popViewControllerAnimated:true];  //跳回上一页
    });
    
}


- (void)startInitWKWebView
{
    [self initWKWebView];
    
    [self initProgressView];
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (void)initWKWebView
{
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = [WKUserContentController new];
    
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    preferences.minimumFontSize = 30.0;
    configuration.preferences = preferences;
    
    self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
    
    //直接网络请求
//    NSString *urlStr = @"http://www.baidu.com";
//        NSString *title = self.itemDatasource;
        NSString *urlStr = itemHTMLURL;
        //urlStr = [urlStr stringByAppendingString:title];
        NSLog(@"urlStr : %@",urlStr);
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
        [self.webView loadRequest:request];
    
    
    //    NSData *data = self.itemDatasource;
    //
    //  b本地文件
    //    // 将请求到的网页数据用loadHTMLString 的方法加载
//    NSString *htmlStr = [[NSString alloc] initWithData:itemHTMLData encoding:NSUTF8StringEncoding];
//
//    NSURL *baseUrl = [NSURL URLWithString:@"file:///assets/"];
//    //[self.webView loadHTMLString:[self.viewModel getHtmlString] baseURL:baseUrl];
//    [self.webView loadHTMLString:htmlStr baseURL:baseUrl];
    //  b本地文件
    
    //本地文件请求
    //    NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
    //    NSURL *fileURL = [NSURL fileURLWithPath:urlStr];
    //    [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
    
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    [self.view addSubview:self.webView];
    
    //    [loadActivity stopAnimating];
    //    [activityBg removeFromSuperview];
    //    [self dismissViewControllerAnimated:true completion:nil];
}

- (void)initProgressView
{
    CGFloat kScreenWidth = [[UIScreen mainScreen] bounds].size.width;
    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 2)];
    progressView.tintColor = [UIColor redColor];
    progressView.trackTintColor = [UIColor lightGrayColor];
    [self.view addSubview:progressView];
    self.progressView = progressView;
}





- (void)rightClick
{
    [self goBack];
}

- (void)dealloc
{
    NSLog(@"%s",__FUNCTION__);
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    // 销毁通知
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"getitemDataNOTIF" object:nil];
    
}
- (void)viewWillDisappear:(BOOL)animated{
    // 销毁通知
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"getitemDataNOTIF" object:nil];
}


- (void)shakeAction
{
    AudioServicesPlaySystemSound (kSystemSoundID_Vibrate);
}

- (void)goBack
{
    [self.webView goBack];
}

#pragma mark - KVO
// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            [self.progressView setProgress:1.0 animated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.hidden = YES;
                [self.progressView setProgress:0 animated:NO];
            });
            
        }else {
            self.progressView.hidden = NO;
            [self.progressView setProgress:newprogress animated:YES];
        }
    }
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSLog(@"拦截点击");
    //    NSURL *URL = navigationAction.request.URL;
    //    NSString *scheme = [URL scheme];
    //    NSLog(@"请求连接  ,%@",scheme);
    //
    //    if ([scheme isEqualToString:@"haleyaction"]) {
    //
    //        [self handleCustomAction:URL];
    //
    //        decisionHandler(WKNavigationActionPolicyCancel);
    //        return;
    //    }
    //    decisionHandler(WKNavigationActionPolicyAllow);
    
    
    
    NSString *strRequest = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];  //请求网址字符串
    NSLog(@"请求连接2  ,%@",strRequest);
    
    // 拦截点击链接
    //hasPrefix:方法来判断使用stringWithCString:方法创建的字符串是否以字母B开始
    if ([strRequest hasPrefix:@"http://youngplus.com.hk/"]) { //[strRequest hasPrefix:@"app://"]
//        NSLog(@"不允许跳转");
//        // 不允许跳转
//        decisionHandler(WKNavigationActionPolicyCancel);
//
//        [self handleCustomAction:strRequest];  //自定义处理URL
        
        NSLog(@"yes youngplus.com.hk 允许跳转");
        // 允许跳转
        decisionHandler(WKNavigationActionPolicyAllow);

    }else if([strRequest hasPrefix:@"http://www.dnawecheck.com/"]){  // 基因检测 打开外部浏览器
        NSLog(@"不允许跳转 基因检测 打开外部浏览器");
        decisionHandler(WKNavigationActionPolicyCancel);
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strRequest]]; //打开外部浏览器
    }else {
        NSLog(@"yes 允许跳转");
        // 允许跳转
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    
    
}


#pragma mark - private method
//- (void)handleCustomAction:(NSURL *)URL
//{
//    NSString *host = [URL host];
//    if ([host isEqualToString:@"scanClick"]) {
//        NSLog(@"扫一扫");
//    } else if ([host isEqualToString:@"shareClick"]) {
//        [self share:URL];
//    } else if ([host isEqualToString:@"getLocation"]) {
//        [self getLocation];
//    } else if ([host isEqualToString:@"setColor"]) {
//        [self changeBGColor:URL];
//    } else if ([host isEqualToString:@"payAction"]) {
//        [self payAction:URL];
//    } else if ([host isEqualToString:@"shake"]) {
//        [self shakeAction];
//    } else if ([host isEqualToString:@"goBack"]) {
//        [self goBack];
//    }
//
//}

- (void)handleCustomAction:(NSString *)URL
{
    // 判断跳转
    //NSString *link_id = @"";
    //用指定字符串分割字符串，返回一个数组
    NSArray *array = [URL componentsSeparatedByString:@"/"];
    //NSLog(@"分割后数组 %@",array);
    NSString *urltitle = [array lastObject];
    NSLog(@"拦截后 文章标题 %@",urltitle);
    
    
    if ([urltitle isEqualToString:@"聯絡young"]) {
        // 聯絡young
        NSLog(@"需要本地处理表单 %@",urltitle);
//        aboutUsSwiftVC *vc_aboutUSswift = [[aboutUsSwiftVC alloc]init];
//        [self.navigationController pushViewController:vc_aboutUSswift animated:YES];   //同一个navigationController。推出子视图
        //MMLog(@"点击了视频%@",link_id);
    }else if ([URL hasPrefix:@"app://item"]) {
        // 单品
        //MMLog(@"点击了单品%@",link_id);
    }else if ([URL hasPrefix:@"app://brand"]) {
        //        // 品牌
        //        link_id = [URL substringFromIndex:[NSString stringWithFormat:@"app://brand"].length];
        //        MMLog(@"点击了品牌%@",link_id);
    }else{
        network *getdata = [[network alloc]init];
        [getdata itemVcgetJsonData:@"title" item:urltitle];  //获取子页面数据
        [self loadingView];  //等待网络结果动画
    }
}



#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

-(void)loadingView{  //等待网络结果动画
    
    CGRect frame = CGRectMake(0, 0, 100, 100);
    activityBg = [[UIView alloc]initWithFrame:frame];
    activityBg.center = self.view.center;
    activityBg.backgroundColor = [UIColor grayColor];
    activityBg.alpha = 0.7;
    activityBg.layer.cornerRadius = 5.0;
    //[self.view addSubview:activityBg];
    [self.view addSubview:activityBg];
    
    loadActivity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    loadActivity.frame = CGRectMake(30, 30, 40, 40);
    [loadActivity sizeToFit];
    loadActivity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
    [activityBg addSubview:loadActivity];
    [loadActivity startAnimating];
    //     //网络请求 延迟时间
    //    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, 5000*NSEC_PER_MSEC);
    //    // 延迟方法
    //    // 1 delayTime 2 thread 3 代码
    //    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
    //        [loadActivity stopAnimating];
    //        [activityBg removeFromSuperview];
    //        [self dismissViewControllerAnimated:true completion:nil];
    ////        [self setindexdata]; //设置首页数据
    ////        [self setMenuData];
    ////        [self settableView];
    //    });
    
}

-(void)stoploading{
    //加载成功
    dispatch_queue_t q2 = dispatch_get_main_queue();  //get 主线程
    //    2 add Queue
    dispatch_async(q2, ^{
        [self->loadActivity stopAnimating];
        [self->activityBg removeFromSuperview];
    });

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
